<template>
  <base-breadcrumb :title="titleName">
    <searchData :search-data="searchArr" @search="search" />

    <a-card :bordered="false">
      <!-- <title-name title="分包商进出场台账列表" /> -->

      <div class="table-operator">
        <a-button v-btnPermission="'pm_018_add_01'" type="primary" icon="plus" :loading="loading" @click="handleAdd">
          新增进场分包商
        </a-button>
      </div>
      <div class="pub-table-select-count">
        <a-icon type="info-circle" theme="twoTone" />
        <span style="margin-right: 12px">
          分包商总计：<span class="totalNum">{{ nodeDeltails.totalCount }} 个</span> | 进场分包商：<span class="totalNum">{{ nodeDeltails.inCount }} 个</span> | 出场分包商：<span class="totalNum"
            >{{ nodeDeltails.entryCount ? nodeDeltails.entryCount : 0 }} 个</span
          >
        </span>
      </div>

      <list-table ref="table" size="default" row-key="id" :columns="columns" :request="loadData" :alert="true" show-size-changer show-quick-jumper show-pagination="auto">
        <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
        <span slot="status" slot-scope="text">
          <a-badge :status="text | statusTypeFilter" :text="text | statusFilter" />
        </span>
        <span slot="description" slot-scope="text">
          <ellipsis :length="8" tooltip>{{ text }}</ellipsis>
        </span>
        <span slot="action" slot-scope="text, record">
          <MoreButton>
            <a v-btnPermission="'pm_018_loo_02'" v-if="['0', '1', '2', '3', '4', '5'].includes(record.statusCode)" @click="handleSub(record)">查看</a>
            <span v-if="['0', '1', '2', '3', '4', '5'].includes(record.statusCode)">
              <a @click="handleReview(record)">审批信息</a>
            </span>
            <span v-if="['1', '4'].includes(record.statusCode)" v-btnPermission="'pm_018_edi_03'">
              <a @click="handleEdit(record)">编辑</a>
            </span>
            <span v-if="['2'].includes(record.statusCode)" v-btnPermission="'pm_018_out_04'">
              <a @click="handleExit(record)">出场</a>
            </span>
            <!-- <span v-if="record.statusCode == '0'" v-btnPermission="'pm_018_out_04'">
              <a-divider type="vertical" /><a @click="handleManage(record)">人员管理</a></span
            > -->
            <span v-if="['2', '3', '4', '5'].includes(record.statusCode) && hideBuquBtn()">
              <a @click="handleAssociatedNode(record)">关联节点</a>
            </span>
            <span v-if="['2', '3', '4', '5'].includes(record.statusCode) && hideBuquBtn()">
              <a @click="handleEditPartial(record)">编辑分部分项</a>
            </span>
            <span v-if="['2', '3', '4', '5'].includes(record.statusCode) && hideBuquBtn()" v-btnPermission="'pm_018_lxr_07'">
              <a @click="handleContacts(record)">修改联系人</a>
            </span>
            <span v-if="hideBuquBtn()" v-btnPermission="'pm_018_exp_08'">
              <a @click="handleExport(record)">导出</a>
            </span>
            <span v-if="hideBuquBtn()" v-btnPermission="'pm_018_pri_09'">
              <BasePrintButton ref="BasePrintButton" type="primary" :before-print-fn="handleBatchPrint" buttonType="a" :params="record" />
            </span>
          </MoreButton>
        </span>
      </list-table>

      <!-- 新增进场分包商、编辑分部分项、编辑 - 弹窗 -->
      <a-modal v-model="visible" :title="modelMap[modalType].title" destroy-on-close :width="1000" @cancel="handleCancel">
        <template slot="footer">
          <a-button key="back" @click="handleCancel">
            取消
          </a-button>
          <a-button key="submit" type="primary" :loading="loading" @click="handleOk">
            {{ modelMap[modalType].submitText }}
          </a-button>
        </template>
        <a-form-model ref="form1" :model="form" :rules="rules">
          <a-row :gutter="24">
            <a-col :md="24" :sm="24">
              <a-form-model-item label="所属单位" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="projectId">
                <org-tree-select v-model="form.projectId" is-need-auth check-strictly is-auto-select-first :disabled="modalType === 'editPartial'" @select="selectOrg" />
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row :gutter="24">
            <a-col :md="12" :sm="12">
              <a-form-model-item label="分包商名称" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="subcontractorId">
                <a-select
                  v-model="form.subcontractorId"
                  placeholder="请选择"
                  show-search
                  :filter-option="filterOption"
                  :default-active-first-option="false"
                  :disabled="modalType === 'editPartial'"
                  @popupScroll="scrollMore"
                  @search="fetchUser"
                  @change="getSubOrg"
                >
                  <a-icon v-if="loadingState.isSubcontractor" slot="suffixIcon" style="color: #096dd9" type="loading" />
                  <a-select-option v-for="item in subcontractorsName" :key="item.id" :value="item.subcontractorsId">
                    {{ item.subcontractors }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :md="12" :sm="12">
              <a-form-model-item label="合作事项" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="matters">
                <BaseInput v-if="typeof form.matters === 'string'" :value="processTreeSelect(form.matters)" disabled :title="processTreeSelect(form.matters)" />
                <a-tree-select
                  v-else
                  v-model="form.matters"
                  style="width: 100%"
                  :tree-data="treeData"
                  multiple
                  label-in-value
                  :replace-fields="{ children: 'children', title: 'name', key: 'id', value: 'id' }"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  :disabled="modalType === 'editPartial'"
                  placeholder="请选择"
                />
              </a-form-model-item>
            </a-col>
            <a-col :md="12" :sm="12">
              <a-form-model-item label="分包商资源代表" prop="subResourceRepresent" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }">
                <BaseInput v-model="form.subResourceRepresent" placeholder="请输入" :max-length="100" />
              </a-form-model-item>
            </a-col>
            <a-col :md="12" :sm="12">
              <a-form-model-item label="联系方式" prop="contactInformation" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }">
                <BaseInput v-model="form.contactInformation" placeholder="请输入" :max-length="100" />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :md="12" :sm="12">
              <a-form-model-item label="拟进场时间" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="planEntryDate">
                <a-date-picker v-model="form.planEntryDate" :disabled="modalType === 'editPartial'" @change="planEntryDateTrans" />
              </a-form-model-item>
            </a-col>
            <a-col :md="12" :sm="12">
              <a-form-model-item label="定标时间" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="calibrationTime">
                <a-date-picker v-model="form.calibrationTime" :disabled="modalType === 'editPartial'" @change="outsTime" />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="18">
            <a-col :md="18" :sm="18">
              <a-form-model-item ref="partialAllNameList" label="分部分项" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="partialAllNameList">
                <!-- 这个地方直接绑定选项名的汉字(description) -->
                <PartialTreeSelect
                  v-model="form.partialAllNameList"
                  :tree-data="partialTree"
                  :replace-fields="{
                    children: 'childrenLabelVO',
                    title: 'name',
                    key: 'id',
                    value: 'description'
                  }"
                  placeholder="请选择分部分项"
                />
              </a-form-model-item>
            </a-col>
            <a-col :md="24" :sm="24">
              <a-form-model-item ref="calibrationId" label="定标文件" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="calibrationId">
                <l-table :need-chinese-name="true" :upload-arrys.sync="uploadArrys2" :business-code="businessCode2" :disabled="modalType === 'editPartial'" :multiple="false" count="1" @fileArrysData="fileArrysData2" />
              </a-form-model-item>
            </a-col>
            <a-col :md="24" :sm="24">
              <a-form-model-item ref="approveId" label="现场审批表" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="approveId">
                <l-table :need-chinese-name="true" :upload-arrys.sync="uploadArrys1" :business-code="businessCode1" :disabled="modalType === 'editPartial'" :multiple="false" count="1" @fileArrysData="fileArrysData1" />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :md="12" :sm="12">
              <a-form-model-item label="关联节点" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }">
                <a-button :disabled="!form.projectId || modalType === 'editPartial'" type="primary" @click="handleSelectAssociated">
                  选择节点
                </a-button>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </a-modal>

      <!-- 出场弹窗 -->
      <a-modal v-model="exitModelVisible" :title="exitModelMap[exitModelType].title" destroy-on-close :width="800">
        <template slot="footer">
          <a-button key="back" @click="handleCancels">
            取消
          </a-button>
          <a-button key="submit" type="primary" :loading="exitLoading" @click="handleOks">
            {{ exitModelMap[exitModelType].submitText }}
          </a-button>
        </template>
        <a-form-model ref="form2" :model="forms" :rules="rulesOut">
          <a-row :gutter="24">
            <a-col :md="24" :sm="24">
              <a-form-model-item label="所属单位" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="projectId">
                <org-tree-select v-model="forms.projectId" is-need-auth check-strictly is-auto-select-first disabled @select="selectOrg" />
              </a-form-model-item>
            </a-col>
          </a-row>
          <!-- <a-row :gutter="24">
            <a-col :md="12" :sm="12">
              <a-form-model-item label="分公司" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }">
                <BaseInput v-model="forms.branch" disabled />
              </a-form-model-item>
            </a-col>
            <a-col :md="12" :sm="12">
              <a-form-model-item label="项目" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }">
                <BaseInput v-model="forms.projectName" disabled />
              </a-form-model-item>
            </a-col>
          </a-row> -->
          <a-row :gutter="24">
            <a-col :md="12" :sm="12">
              <a-form-model-item label="分包商名称" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }">
                <BaseInput v-model="forms.subcontractors" disabled />
              </a-form-model-item>
            </a-col>
            <a-col :md="12" :sm="12">
              <a-form-model-item label="合作事项" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }">
                <BaseInput :value="processTreeSelect(forms.matters)" disabled :title="forms.matters" />
              </a-form-model-item>
            </a-col>
            <a-col :md="12" :sm="12">
              <a-form-model-item label="分包商资源代表" prop="subResourceRepresent" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }">
                <BaseInput v-model="forms.subResourceRepresent" placeholder="请输入" :max-length="100" />
              </a-form-model-item>
            </a-col>
            <a-col :md="12" :sm="12">
              <a-form-model-item label="联系方式" prop="contactInformation" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }">
                <BaseInput v-model="forms.contactInformation" placeholder="请输入" :max-length="100" />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :md="12" :sm="12">
              <a-form-model-item label="实际进场时间" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }">
                <a-date-picker v-model="forms.entryTime" disabled style="width: 100%" />
              </a-form-model-item>
            </a-col>
            <a-col :md="12" :sm="12">
              <a-form-model-item label="拟出场时间" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="planAppearanceDate">
                <!-- <a-date-picker :disabled-date="disabledDate"  v-model="startValue" @change="outsTimes" style="width: 100%;" /> -->
                <a-date-picker v-model="forms.planAppearanceDate" format="YYYY-MM-DD" :disabled-date="disabledDate" @change="outsTimes" />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :md="24" :sm="24">
              <a-form-model-item label="履约情况及进度" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="performanceProgress">
                <a-textarea placeholder="请输入" v-model="forms.performanceProgress" :auto-size="{ minRows: 2, maxRows: 6 }" :maxLength="1000" />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :md="24" :sm="24">
              <a-form-model-item ref="exitApprovalId" label="出场审批表" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="exitApprovalId">
                <l-table :is-limit="true" :need-chinese-name="true" :multiple="false" :business-code="businessCode3" @fileArrysData="fileArrysData3" />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </a-modal>

      <!-- 修改联系人弹窗 -->
      <a-modal v-if="contactsVisible" destroy-on-close title="修改联系人" :visible="true" width="1000px" @cancel="contactsVisible = false">
        <template slot="footer">
          <a-button key="back" @click="contactsVisible = false">
            取消
          </a-button>
          <a-button key="submit" :loading="loading" type="primary" @click="contactsHandleOk">
            确认
          </a-button>
        </template>
        <a-form-model ref="ruleForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="contactsRules" :model="contactsForm">
          <a-row>
            <a-col :md="12" :sm="12">
              <a-form-model-item label="分包商资源代表" prop="subResourceRepresent">
                <BaseInput v-model="contactsForm.subResourceRepresent" placeholder="请输入" :max-length="100" />
              </a-form-model-item>
            </a-col>
            <a-col :md="12" :sm="12">
              <a-form-model-item label="联系方式" prop="contactInformation">
                <BaseInput v-model="contactsForm.contactInformation" placeholder="请输入" :max-length="100" />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </a-modal>

      <!-- 选择关联节点 -->
      <SelectAssociatedNode :visible.sync="associatedVisible" :data="associatedData" @select="associatedNodeSelect" />
      <!-- 选择关联节点 -->
    </a-card>
    <ApprovalDetails title="审批详情" :business-id="businessId" :visible="visibleApprove" @cancel="visibleApprove = false" @confirm="visibleApprove = false" />
    <!-- 选择审批人的弹窗 -->
    <selectApprover :isCloseUpper="false" :businessId="businessId" :processConfig="setProcessConfig" @closevisible="closeSelectApprover"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import { Ellipsis } from '@/components'
import { printEntryExitLedger } from '@/api/subcontractors/subcontractors'
import {
  getSubcontractorsList,
  addSubcontractors,
  editEntrySubcontractors,
  editSubcontractors,
  getSubcontractorsTotal,
  getLoborName,
  partialList,
  partial,
  getSubcontractorsOne,
  editUpdateContact
} from '@/api/subcontractors/standing'
import OrgTreeSelect from '@/components/OrgTreeSelect'
import ARow from 'ant-design-vue/es/grid/Row'
import moment from 'moment'
import SelectAssociatedNode from './components/SelectAssociatedNode'
import api from '@/api/project/typeMaintenance'
import MoreButton from '@/components/MoreButton'
import PartialTreeSelect from './components/PartialTreeSelect.js'
import { unionApiUrl } from '@/api/config.js'
import Vue from 'vue'
import { downloadPost } from '@/utils/request2'
import { planProducer } from '@/api/config'
import axios from 'axios'
import ApprovalDetails from './approvalDetails'

export default {
  name: 'a' + Date.now(),
  components: {
    ARow,
    Ellipsis,
    SelectAssociatedNode,
    MoreButton,
    PartialTreeSelect,
    ApprovalDetails
  },
  data() {
    return {
      columns: [
        {
          title: '序号',
          width: 65,
          scopedSlots: { customRender: 'serial' }
        },
        {
          title: '分包商名称',
          width: 100,
          dataIndex: 'subcontractors'
        },
        {
          title: '项目',
          width: 100,
          dataIndex: 'projectName'
        },
        {
          title: '分公司',
          width: 100,
          dataIndex: 'branch'
        },
        {
          title: '合作事项',
          dataIndex: 'matters',
          width: 100,
          customRender: (text, record, index) => {
            return this.processTreeSelect(text)
          }
        },
        {
          title: '实际进场时间',
          width: 100,
          dataIndex: 'entryTime'
        },
        {
          title: '定标时间',
          width: 100,
          dataIndex: 'calibrationTime'
        },
        {
          title: '实际出场时间',
          width: 100,
          dataIndex: 'outTime'
        },
        {
          title: '创建时间',
          width: 100,
          dataIndex: 'createTime'
        },
        {
          title: '状态',
          width: 100,
          dataIndex: 'statusName'
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 180,
          scopedSlots: { customRender: 'action' }
        }
      ],
      loadingState: {
        isSubcontractor: false
      },
      loading: false,
      uploadArrys1: [], // 现场审批表
      uploadArrys2: [], // 定标文件

      businessCode1: 'PM05',
      businessCode2: 'PM06',
      businessCode3: 'PM08',
      companyNames: [],

      pageNo: 1,
      pageSize: 20, // 投标单位选择
      totalPage: 0,
      totalSize: 0,

      // 进场
      form: {
        matters: [],
        subContractorOrgId: '',
        approveId: '',
        calibrationId: ''
      },
      // 出场
      forms: {
        exitApprovalId: ''
      },
      rules: {
        subResourceRepresent: [{ required: true, message: '请输入分包商资源代表', trigger: 'change' }],
        contactInformation: [{ required: true, message: '请输入联系方式', trigger: 'change' }],
        branchId: [{ required: true, message: '请选择分公司', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择项目', trigger: 'change' }],
        subcontractorId: [{ required: true, message: '请选择分包商名称', trigger: 'blur' }],
        matters: [{ required: true, message: '请输入合作事项', trigger: 'change' }],
        entryTime: [{ required: true, message: '请选择进场时间', trigger: 'change' }],
        planEntryDate: [{ required: true, message: '请选择拟进场时间', trigger: 'change' }],
        calibrationTime: [{ required: true, message: '请选择定标时间', trigger: 'change' }],
        partialAllNameList: [{ required: true, message: '请选择分部分项', trigger: 'change' }],
        calibrationId: [{ required: true, message: '请上传定标文件', trigger: 'change' }]
      },
      // 出场验证
      rulesOut: {
        subResourceRepresent: [{ required: true, message: '请输入分包商资源代表', trigger: 'change' }],
        contactInformation: [{ required: true, message: '请输入联系方式', trigger: 'change' }],
        planAppearanceDate: [{ required: true, message: '请选择拟出场时间', trigger: 'change' }],
        performanceProgress: [{ required: true, message: '请输入履约情况及进度', trigger: 'change' }]
        // exitApprovalId: [{ required: true, message: '请上传出场审批表', trigger: 'change' }]
      },

      onlyCompany: 0,
      searchArr: [
        {
          name: '所属单位',
          valueKey: 'searchQuery',
          type: OrgTreeSelect
        },
        {
          name: '分包商名称',
          value: 'subcontractorName',
          type: 'input'
        },
        {
          name: '状态',
          value: 'statusCode',
          type: 'select',
          data: [
            {
              value: '0',
              label: '进场-审批中'
            },
            {
              value: '1',
              label: '进场-审批不通过'
            },
            {
              value: '2',
              label: '进场'
            },
            {
              value: '3',
              label: '出场-审批中'
            },
            {
              value: '4',
              label: '出场-审批不通过'
            },
            {
              value: '5',
              label: '出场'
            }
          ]
        }
      ],
      nodeDeltails: {}, // 分包商汇总详情
      titleName: '',
      // create model
      visible: false,
      exitLoading: false,
      exitModelVisible: false,
      exitModelType: 'add',
      exitModelMap: {
        add: {
          title: '分包商出场设置',
          submitText: '确定出场'
        },
        edit: {
          title: '编辑分包商出场设置',
          submitText: '确定'
        }
      },
      contactsVisible: false,
      mdl: null,
      mdls: null,
      startValue: '',
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return getSubcontractorsList(requestParameters).then(res => {
          return res
        })
      },
      selectedRowKeys: [],
      selectedRows: [],
      isEdit: false,
      calType: [],
      subcontractorsName: [],

      queryData: {
        statusCode: '0'
      },

      entryTime: '', // 进场时间
      outTime: '', // 出场时间
      outTimes: '', // 修改出场时间
      calibrationTime: '', // 修改出场时间

      exitApprovalId: '', // 出场审批表id,
      // 关联节点选择显示隐藏、
      associatedVisible: false,
      associatedData: {},
      // 关联节点
      associatedNode: [],
      treeData: [],
      // 模态框类型
      modalType: 'add',
      // 配合上述【模态框类型】
      modelMap: {
        add: {
          title: '新增进场分包商',
          submitText: '确定入场'
        },
        editEntry: {
          title: '编辑进场分包商',
          submitText: '确定'
        },
        editPartial: {
          title: '编辑分部分项',
          submitText: '确定'
        }
      },
      // 分部分项树
      partialTree: [],
      contactsForm: {
        subResourceRepresent: '',
        contactInformation: ''
      },
      contactsRules: {
        subResourceRepresent: [{ required: true, message: '请输入分包商资源代表', trigger: 'change' }],
        contactInformation: [{ required: true, message: '请输入联系方式', trigger: 'change' }]
      },
      unionApiUrl,
      token: '',
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null,
      visibleApprove: false
    }
  },
  filters: {
    statusFilter(type) {
      return statusMap[type].text
    },
    statusTypeFilter(type) {
      return statusMap[type].status
    }
  },
  async created() {
    this.getSubtotalDeltails()
    this.getTreeData()
    this.getPartialTree()
    this.token = Vue.getAcloudProvider().getAccessToken()
  },
  // 由于组件父级用了 keep-alive 导致修改流程配置时 config 值无法重新拉取
  async activated() {
    /**
     * 提交选择审批人，流程加急，返回值
     * 是 否 1
     * 是 是 2
     * 否 是 3
     * 否 否 4
     */
    //获取通过获取流程配置值
    this.processEntryConfig = await this.$getConfigFn('subcontractor_approach_approval_process')
    this.processExitConfig = await this.$getConfigFn('subcontractor_exit_approval_process')
    console.log('processEntryConfig', this.processEntryConfig)
    console.log('processExitConfig', this.processExitConfig)
  },
  watch: {
    startValue(val) {
      console.log('startValue', val)
    },
    endValue(val) {
      console.log('endValue', val)
    },
    associatedVisible: {
      handler(newV, oldV) {
        if (newV) {
          this.associatedNode = []
        }
      }
    },
    'form.partialAllNameList': {
      handler(val) {
        if (Array.isArray(val) && val.length > 0) {
          this.$refs.form1?.clearValidate('partialAllNameList')
        }
      }
    }
  },
  methods: {
    selectOrg(val) {
      if (val && val.length) {
        this.form.projectId = val[val.length - 1].projectId
        this.form.branchId = val[val.length - 2].orgId
        this.$refs.form1.clearValidate('projectId')
        this.handleBranchComChanged()
      }
    },
    processTreeSelect(val) {
      if (val) {
        try {
          let r = JSON.parse(val)
          return r.map(v => v.label).join(',')
        } catch (e) {
          return val
        }
      }
      return ''
    },
    async getTreeData() {
      let res = await api.labelTreeList({ enabledCode: '1' })
      if (res.code === 200) {
        this.treeData = this.digui(res.data)
      }
    },
    async getPartialTree() {
      let res = await partialList()
      if (res.code === 200) {
        this.partialTree = res.data
      }
    },
    digui(list) {
      let r = []
      list.map(v => {
        if (!v.disabled) {
          let r2 = this.$clone(v)
          if (v.children && v.children.length) {
            let list = this.digui(v.children)
            if (list.length) {
              r2.children = list
              r2.disabled = true
            } else {
              r2.children = []
              r2.disabled = false
            }
          } else {
            r2.disabled = false
          }
          r.push(r2)
        }
      })
      return r
    },
    getSubOrg(val) {
      const target = this.subcontractorsName.find(item => item.subcontractorsId === val)
      this.form.subContractorOrgId = target.subContractorOrgId
    },
    // 分包商名称可搜索
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    handleChangeCompanys(val) {
      this.queryData.branchComId = val.key
    },
    fetchUser(val) {
      this.pageNo = 1
      this.totalPage = 0
      this.subcontractorsName = []
      this.getLoborNames(val)
      // getLoborName({ subcontractorName: val, status: '0', branchComId: this.form.branchId || '' }).then((res) => {
      //   if (res.code === 200 || res.data.code === 200) {
      //     if (res.data) {
      //       this.subcontractorsName = res.data
      //     }
      //   }
      // })
    },
    // 下拉滚动加载
    scrollMore(e) {
      const { target } = e
      var total = target.scrollTop + target.offsetHeight
      var scrollHeight = target.scrollHeight

      // this.pageNo是当前页 this.totalPage是总页数
      if (total >= scrollHeight - 1 && total < scrollHeight + 1 && this.pageNo <= this.totalPage) {
        this.pageNo = this.pageNo + 1
        this.getLoborNames() // 调用api方法
      }
    },
    handleBranchComChanged() {
      this.pageNo = 1
      this.totalPage = 0
      this.subcontractorsName = []
      this.getLoborNames()
    },
    getLoborNames(val) {
      let that = this
      this.loadingState.isSubcontractor = true
      getLoborName({
        pageNo: that.pageNo,
        pageSize: that.pageSize,
        branchComId: this.form.branchId || '',
        status: '0',
        subcontractorName: val
      })
        .then(res => {
          this.loadingState.isSubcontractor = false
          if (res.code === 200 || res.data.code === 200) {
            if (res.data) {
              // 过滤掉没有subcontractors的数据，避免select组件报错、异常
              const list = res.data.filter(item => item.subcontractors)
              that.subcontractorsName = that.subcontractorsName.concat(list)
            }
            that.totalPage = res.totalPage
            that.totalSize = res.totalSize
          }
        })
        .catch(() => {
          this.loadingState.isSubcontractor = false
        })
    },

    fileArrysData1(val) {
      if (val.length) {
        this.form.approveId = val[0].commonId
      } else {
        this.form.approveId = ''
      }
      this.$refs.approveId.onFieldChange()
    },
    fileArrysData2(val) {
      if (val.length) {
        this.form.calibrationId = val[0].commonId
      } else {
        this.form.calibrationId = ''
      }
      this.$refs.calibrationId.onFieldChange()
    },
    fileArrysData3(val) {
      if (val.length) {
        this.forms.exitApprovalId = val[0].commonId
      } else {
        this.forms.exitApprovalId = ''
      }
      this.$refs.exitApprovalId.onFieldChange()
    },
    getSubtotalDeltails() {
      getSubcontractorsTotal(this.queryParam).then(res => {
        this.nodeDeltails = res.data
      })
    },
    search(val) {
      // 搜索
      let _this = this
      _this.queryParam = val
      if (_this.queryParam.subcontractorName === '') {
        _this.queryParam.subcontractorName = void 0
      }
      _this.getSubtotalDeltails()
      _this.$refs.table.refresh(true)
    },
    // 新增进场分包商
    handleAdd() {
      this.modalType = 'add'
      this.visible = true
      this.uploadArrys1 = []
      this.uploadArrys2 = []
      this.mdl = null
      this.form = {
        matters: [],
        subContractorOrgId: '',
        approveId: '',
        calibrationId: ''
      }
      this.isEdit = false
    },
    disabledDate(current) {
      return current < moment(this.forms.entryTime)
    },
    handleStartOpenChange(open) {
      if (!open) {
        this.endOpen = true
      }
    },
    // 进场编辑 & 出场编辑
    async handleEdit(record) {
      // 查询详情
      const res = await getSubcontractorsOne({ id: record.id })
      if (res.code !== this.SUCCESS_CODE) {
        this.$message.error(res.message)
        return
      }
      // 进场编辑
      if (record.statusCode === '1') {
        this.modalType = 'editEntry'

        this.uploadArrys2 = res.data.calibration
        this.uploadArrys1 = res.data.approve

        this.visible = true

        // 处理之前字段不对应
        try {
          let obj = { ...res.data, matters: JSON.parse(res.data.matters), subcontractorId: res.data.subcontractorId, calibrationId: null, approveId: null }

          if (this.uploadArrys2 && this.uploadArrys2.length > 0) {
            obj.calibrationId = res.data.calibrationId
          }

          if (this.uploadArrys1 && this.uploadArrys1.length > 0) {
            obj.approveId = res.data.approveId
          }
          this.form = obj
        } catch (error) {
          let obj = { ...res.data, matters: res.data.matters, subcontractorId: res.data.subcontractorId, calibrationId: null, approveId: null }

          if (this.uploadArrys2 && this.uploadArrys2.length > 0) {
            obj.calibrationId = res.data.calibrationId
          }

          if (this.uploadArrys1 && this.uploadArrys1.length > 0) {
            obj.approveId = res.data.approveId
          }
          this.form = obj
        }
        this.subcontractorsName = []
        this.getLoborNames()

        return
      }
      // 出场编辑
      if (record.statusCode === '4') {
        this.exitModelVisible = true
        this.exitModelType = 'edit'

        this.forms = {
          ...res.data,
          branch: res.data.branchName,
          subcontractors: res.data.subcontractorName
        }
      }
    },
    // 审批信息
    handleReview(record) {
      this.visibleApprove = true
      this.businessId = record.id
      
      // // 进场相关（原通用部分）
      // if (['0', '1', '2'].includes(record.statusCode)) {
      //   this.$bus.$emit('showApprovalDetailsDialog', record.id)
      //   return
      // }
      // // 出场相关
      // if (['3', '4', '5'].includes(record.statusCode)) {
      //   this.$bus.$emit('showApprovalDetailsDialog', record.id + '_out')
      //   return
      // }
    },
    // 出场
    async handleExit(record) {
      // 查询详情
      const res = await getSubcontractorsOne({ id: record.id })
      if (res.code !== this.SUCCESS_CODE) {
        this.$message.error(res.message)
        return
      }

      this.exitModelVisible = true
      this.exitModelType = 'add'
      this.forms = {
        ...res.data,
        branch: res.data.branchName,
        subcontractors: res.data.subcontractorName
      }
    },
    // /**
    //  * 人员管理
    //  */
    // handleManage(e) {
    //   this.$router.push({
    //     path: '/subcontractors/employeeManage',
    //     query: {
    //       id: e.id,
    //       projectOrgId: e.projectOrgId,
    //     },
    //   })
    // },

    // 拟进场时间
    planEntryDateTrans(val) {
      this.form.planEntryDate = val.format('YYYY-MM-DD')
    },
    inTime(val) {
      // 进场时间
      this.form.entryTime = val.format('YYYY-MM-DD')
    },
    outsTime(val) {
      // 出场时间
      this.form.calibrationTime = val.format('YYYY-MM-DD')
    },
    outsTimes(val) {
      // 修改出场时间
      this.forms.outTime = val.format('YYYY-MM-DD')
    },
    // <selectApprover> 组件的关闭事件
    closeSelectApprover() {
      console.log('closeSelectApprover')
      this.$refs.table.refresh(true)
      this.businessId = null
      this.setProcessConfig = null
    },

    // 新增进场分包商 & 编辑入场 & 编辑分部分项
    handleOk() {
      // 防止 closeSelectApprover 不触发，保险起见
      this.businessId = null
      this.setProcessConfig = null
      // 新增
      if (this.modalType === 'add') {
        this.$refs.form1.validate((err, values) => {
          if (err) {
            if (this.loading) return
            this.loading = true

            // 审批流程组件提交逻辑
            this.submitApprovalConfirm(this.processEntryConfig, flag => {
              // 如果不需要审批，直接返回
              if (!flag) {
                this.loading = false
                return
              }
              // 业务提交逻辑
              let data = this.$clone(this.form)
              data.matters = JSON.stringify(data.matters)
              data.nodeIds = this.associatedNode
              data.partialAllNameList = data.partialAllNameList
              if (!data.approveId) {
                data.approveId = null
              }

              addSubcontractors(data)
                .then(res => {
                  this.loading = false
                  if (res.code == 200) {
                    this.handleCancel()
                    this.$refs.table.refresh(true)
                    this.$message.success('新增成功！')
                    // 流程组件需要
                    this.businessId = res.data.id
                    this.setProcessConfig = this.processEntryConfig
                  } else {
                    this.$message.error('新增失败！')
                  }
                })
                .catch(() => {
                  this.loading = false
                })
            })
          } else {
            this.$noticeWarning('请填写完整')
          }
        })
        return
      }

      // 编辑入场
      if (this.modalType === 'editEntry') {
        this.$refs.form1.validate((err, values) => {
          if (err) {
            if (this.loading) return
            this.loading = true

            // 审批流程组件提交逻辑
            this.submitApprovalConfirm(this.processEntryConfig, flag => {
              // 如果不需要审批，直接返回
              if (!flag) {
                this.loading = false
                return
              }
              // 业务提交逻辑
              let data = this.$clone(this.form)
              data.matters = JSON.stringify(data.matters)
              data.nodeIds = this.associatedNode
              data.partialAllNameList = data.partialAllNameList
              if (!data.approveId) {
                data.approveId = null
              }
              if (!data.calibrationId) {
                data.calibrationId = null
              }
              console.log('entry.edit.submit.data', data)

              editEntrySubcontractors(data)
                .then(res => {
                  this.loading = false
                  if (res.code == 200) {
                    this.handleCancel()
                    this.$refs.table.refresh(true)
                    this.$message.success('编辑成功！')
                    // 流程组件需要
                    this.businessId = res.data.id
                    this.setProcessConfig = this.processEntryConfig
                  } else {
                    this.$message.error('编辑失败！')
                  }
                })
                .catch(() => {
                  this.loading = false
                })
            })
          } else {
            this.$noticeWarning('请填写完整')
          }
        })
        return
      }

      // 编辑分部分项
      if (this.modalType === 'editPartial') {
        // 编辑分部分项
        this.$refs.form1.validateField('partialAllNameList', valid => {
          if (!valid) {
            this.loading = true
            partial({
              inAndOutId: this.form.id,
              partialAllNameList: this.form.partialAllNameList
            })
              .then(res => {
                if (res.code == 200) {
                  this.handleCancel()
                  // 刷新表格
                  this.$refs.table.refresh(true)
                  this.$message.success('编辑成功！')
                } else {
                  this.$message.error('编辑失败！')
                }
              })
              .finally(() => {
                this.loading = false
              })
          }
        })
      }
    },

    // 出场提交
    handleOks() {
      // 防止 closeSelectApprover 不触发，保险起见
      this.businessId = null
      this.setProcessConfig = null
      // 新增
      if (this.exitModelType === 'add') {
        this.$refs.form2.validate((valid, value) => {
          if (valid) {
            this.exitLoading = true
            // 审批流程组件提交逻辑
            this.submitApprovalConfirm(this.processExitConfig, flag => {
              // 如果不需要审批，直接返回
              if (!flag) {
                this.exitLoading = false
                return
              }
              // 业务逻辑
              editSubcontractors(this.forms)
                .then(res => {
                  if (res.code == 200) {
                    this.exitModelVisible = false
                    // 刷新表格
                    this.$refs.table.refresh(true)
                    this.$message.success('操作成功！')
                    // 流程组件需要
                    this.businessId = res.data.id + '_out'
                    this.setProcessConfig = this.processExitConfig
                  } else {
                    this.$message.error('操作失败！')
                    // 重置表单数据
                    this.exitModelVisible = false
                  }
                })
                .finally(() => {
                  this.exitLoading = false
                })
            })
          }
        })
        return
      }

      // 编辑
      if (this.exitModelType === 'edit') {
        this.$refs.form2.validate((valid, value) => {
          if (valid) {
            this.exitLoading = true
            // 审批流程组件提交逻辑
            this.submitApprovalConfirm(this.processExitConfig, flag => {
              // 如果不需要审批，直接返回
              if (!flag) {
                this.exitLoading = false
                return
              }
              // 业务逻辑
              editSubcontractors(this.forms)
                .then(res => {
                  if (res.code == 200) {
                    this.exitModelVisible = false
                    // 刷新表格
                    this.$refs.table.refresh(true)
                    this.$message.success('操作成功！')
                    // 流程组件需要
                    this.businessId = res.data.id + '_out'
                    this.setProcessConfig = this.processExitConfig
                  } else {
                    this.$message.error('操作失败！')
                    // 重置表单数据
                    this.exitModelVisible = false
                  }
                })
                .finally(() => {
                  this.exitLoading = false
                })
            })
          }
        })
        return
      }
    },
    handleCancel() {
      this.subcontractorsName = []
      this.visible = false
    },
    handleCancels() {
      this.exitModelVisible = false
    },
    // 查看
    handleSub(record) {
      this.$router.push({ path: '/subcontractors/details', query: { id: record.id } })
    },
    // 修改联系人 - 确认
    contactsHandleOk() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          editUpdateContact(this.contactsForm).then(res => {
            this.loading = false
            this.contactsVisible = false
            if (res.code == 200) {
              this.$message.success('编辑成功')
            }
            this.$refs.table.refresh(true)
          })
        } else {
          this.$message.warn('请填写完所有必填项信息')
        }
      })
    },
    /**
     * @description: 选择关联节点
     * @param {void}
     * @return {void}
     */
    handleSelectAssociated() {
      this.associatedVisible = true
      this.associatedData = {
        projectId: this.form.projectId,
        associatedNode: this.associatedNode
      }
    },
    /**
     * @description: 选择节点
     * @param {array} node
     * @return {void}
     */
    associatedNodeSelect(node) {
      this.associatedNode = node
    },
    /**
     * @description: 编辑关联节点
     * @param {object} record 行数据
     * @return {void}
     */
    handleAssociatedNode(record) {
      this.associatedVisible = true
      this.associatedData = {
        projectId: record.projectId,
        inAndOutId: record.id,
        associatedNode: this.associatedNode
      }
    },
    /**
     * @description: 编辑分部分项
     * @param {object} record 行数据
     * @return {void}
     */
    handleEditPartial(record) {
      this.modalType = 'editPartial'
      this.visible = true
      // 查询详情
      getSubcontractorsOne({ id: record.id }).then(res => {
        if (res.code === this.SUCCESS_CODE) {
          this.uploadArrys2 = res.data.calibration
          this.uploadArrys1 = res.data.approve
        }
      })
      // 处理之前字段不对应
      try {
        this.form = { ...record, matters: JSON.parse(record.matters), subcontractorId: record.subcontractorsId }
      } catch (error) {
        this.form = { ...record, matters: record.matters, subcontractorId: record.subcontractorsId }
      }
      this.subcontractorsName = []
      this.getLoborNames()
    },
    // 修改联系人
    async handleContacts(record) {
      const res = await getSubcontractorsOne({ id: record.id })
      if (res.code !== this.SUCCESS_CODE) {
        this.$message.error(res.message)
        return
      }

      this.uploadArrys2 = res.data.calibration
      this.uploadArrys1 = res.data.approve

      this.contactsForm.id = res.data.id
      this.contactsForm.subResourceRepresent = res.data.subResourceRepresent
      this.contactsForm.contactInformation = res.data.contactInformation
      this.contactsVisible = true
    },
    // 批量导出
    async handleExport(record) {
      this.$refs['table'].innerLoading = true
      const params = {
        id: record.id
      }
      // await downloadPost('/sub/doc-export', params, undefined, 'asdf.zip')
      // axios.post('/sub/doc-export?id=' + record.id, null, { responseType: 'arraybuffer', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).then(function(response) {
      //   // let disposition = response.headers['content-disposition']
      //   let blob = new Blob([response.data], { type: 'application/xls' })
      //   let link = document.createElement('a')
      //   link.href = window.URL.createObjectURL(blob)
      //   link.download = 'asdf.zip'
      //   link.click()
      // })

      axios({
        method: 'post',
        url: planProducer + '/sub/doc-export',
        params,
        responseType: 'arraybuffer'
      })
        .then(res => {
          let blob = new Blob([res.data], { type: 'application/xls' })
          let link = document.createElement('a')
          link.href = window.URL.createObjectURL(blob)
          link.download = '台账批量导出.zip'
          link.click()
          link = null
        })
        .finally(() => {
          this.$refs['table'].innerLoading = false
        })
    },
    // 批量打印
    async handleBatchPrint(record) {
      this.$refs['table'].innerLoading = true
      try {
        // this.$refs.BasePrintButton.loadingState.isPrint = true
        const id = record.id
        const res = await printEntryExitLedger(id)
        return res.data.content
      } catch (error) {
        this.$warning('打印失败')
        return Promise.reject(error)
      } finally {
        this.$refs['table'].innerLoading = false
      }
    }
  }
}
</script>
